<?php

class QvmappingController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete','loadFields','loadValues','loadObjectValues','loadMaps','addMapValues','delMapValues'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Qvmapping;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Qvmapping']))
		{
			$model->attributes=$_POST['Qvmapping'];
			if($model->save())
				$this->redirect(array('admin'));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Qvmapping']))
		{
			$model->attributes=$_POST['Qvmapping'];
			if($model->save())
				$this->redirect(array('admin'));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'index' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Qvmapping');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Qvmapping('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Qvmapping']))
			$model->attributes=$_GET['Qvmapping'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Qvmapping::model()->findByPk((int)$id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='qvmapping-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}

        public function actionLoadFields(){
            if(isset($_POST['Qvmapping']['qvm_docName'])){
                ini_set('soap.wsdl_cache_enabled',0);

                $client=new beeyeQvDocumentService(Yii::app()->params->SOAPServerBeeye,array('soap_version'=>SOAP_1_1,'trace'=>1,'exceptions'=>1));//,'location'=>'http://tempuri.org'));
                $client->soap_defentcoding='UTF-8';

                $myFields = new GetbeeyeQvFieldList();
                $myFields->_docName=$_POST['Qvmapping']['qvm_docName'];

                $fieldList = $client->GetbeeyeQvFieldList($myFields);
                
                foreach($fieldList->GetbeeyeQvFieldListResult->beeyeQvField as $beeyeQvFields){
                    $DocName = strtoupper($beeyeQvFields->DocName);
                    $FieldName = $beeyeQvFields->FieldName;
                    if(!is_Object(Qvfields::model()->find('qvf_docName = :docName AND qvf_fieldName = :fieldName',array(':docName'=>$DocName,':fieldName'=>$FieldName)))){
                        $saveField = new Qvfields();
                        $saveField->qvf_docName = $DocName;
                        $saveField->qvf_fieldName = $FieldName;
                        $saveField->save();
                    }
                }

                $data = Qvfields::model()->findAll('qvf_docName = :docName',array(':docName'=>strtoupper($myFields->_docName)));

                $data=CHtml::listData($data,'qvf_id','qvf_fieldName');
                foreach($data as $value=>$name)
                {
                    echo CHtml::tag('option',array('value'=>$value),CHtml::encode($name),true);
                }
            }
        }


        public function actionLoadValues(){
            if (Yii::app()->request->isAjaxRequest) {
                if(isset($_POST['id'])){
                    if($_POST['id']!="0"){
                        try{
                            ini_set('soap.wsdl_cache_enabled',0);

                            $client=new beeyeQvDocumentService(Yii::app()->params->SOAPServerBeeye,array('soap_version'=>SOAP_1_1,'trace'=>1,'exceptions'=>1));//,'location'=>'http://tempuri.org'));
                            $client->soap_defentcoding='UTF-8';

                            $QvFieldRecord = Qvfields::model()->findByPK($_POST['id']);
                            $myFieldName = $QvFieldRecord->qvf_fieldName;

                            $myValues = new GetbeeyeQvFieldValueList();
                            $myValues->_docName=$QvFieldRecord->qvf_docName;
                            $myValues->_fieldName=$myFieldName;

                            $valueList = $client->GetbeeyeQvFieldValueList($myValues);
                            //var_dump($valueList->GetbeeyeQvFieldValueListResult->beeyeQvValue);
                            if(count($valueList->GetbeeyeQvFieldValueListResult->beeyeQvValue)>1){
                                foreach($valueList->GetbeeyeQvFieldValueListResult->beeyeQvValue as $beeyeQvValues){
                                    $FieldValue = $beeyeQvValues->FieldValue;
                                    //var_dump($beeyeQvValues);
                                    if(!is_Object(Qvvalues::model()->find('qvf_id = :qvf_id AND qvv_fieldValue = :fieldValue',array(':qvf_id'=>$_POST['id'],':fieldValue'=>$FieldValue)))){
                                        $saveField = new Qvvalues();
                                        $saveField->qvf_id = $_POST['id'];
                                        $saveField->qvv_fieldValue = $FieldValue;
                                        $saveField->save();
                                    }
                                }
                            }else{
                                
                            }
                        }
                        catch(Exception $e){
                            echo $e;
                        }
                    }

                    $myCriteria = new CDbCriteria(
                            array(
                                'condition'=>'qvf_id = '.$_POST['id'],
                                'order'=>'qvv_fieldValue ASC',
                            )
                    );

                    $data = Qvvalues::model()->findAll($myCriteria);

                    $data=CHtml::listData($data,'qvv_id','qvv_fieldValue');
                    foreach($data as $value=>$name)
                    {
                        echo CHtml::tag('li',array('id'=>$value),CHtml::encode($name),true);
                        //$qvvalues[]=array('label' => $name, 'value' => $value);
                    }                                        
                }                
                //echo json_encode($qvvalues);                
                Yii::app()->end();
            }else {
                throw new CHttpException(400, 'Invalid request.');
            }
        }
        
        public function actionLoadObjectValues(){
            if (Yii::app()->request->isAjaxRequest) {
                if(isset($_POST['id'])){
                    if($_POST['id']!="0"){
                        try{
                            ini_set('soap.wsdl_cache_enabled',0);

                            $client=new beeyeQvDocumentService(Yii::app()->params->SOAPServerBeeye,array('soap_version'=>SOAP_1_1,'trace'=>1,'exceptions'=>1));//,'location'=>'http://tempuri.org'));
                            $client->soap_defentcoding='UTF-8';

                            $QvFieldRecord = Qvfields::model()->findByPK($_POST['id']);
                            $myFieldName = $QvFieldRecord->qvf_fieldName;

                            $myValues = new GetbeeyeQvFieldValueList();
                            $myValues->_docName=$QvFieldRecord->qvf_docName;
                            $myValues->_fieldName=$myFieldName;

                            $valueList = $client->GetbeeyeQvFieldValueList($myValues);
                            //var_dump($valueList->GetbeeyeQvFieldValueListResult->beeyeQvValue);
                            if(count($valueList->GetbeeyeQvFieldValueListResult->beeyeQvValue)>1){
                                foreach($valueList->GetbeeyeQvFieldValueListResult->beeyeQvValue as $beeyeQvValues){
                                    $FieldValue = $beeyeQvValues->FieldValue;
                                    //var_dump($beeyeQvValues);
                                    if(!is_Object(Qvvalues::model()->find('qvf_id = :qvf_id AND qvv_fieldValue = :fieldValue',array(':qvf_id'=>$_POST['id'],':fieldValue'=>$FieldValue)))){
                                        $saveField = new Qvvalues();
                                        $saveField->qvf_id = $_POST['id'];
                                        $saveField->qvv_fieldValue = $FieldValue;
                                        $saveField->save();
                                    }
                                }
                            }else{
                                
                            }
                        }
                        catch(Exception $e){
                            echo $e;
                        }
                    }

                    $myCriteria = new CDbCriteria(
                            array(
                                'condition'=>'qvf_id = '.$_POST['id'],
                                'order'=>'qvv_fieldValue ASC',
                            )
                    );

                    $data = Qvvalues::model()->findAll($myCriteria);

                    $data=CHtml::listData($data,'qvv_id','qvv_fieldValue');
                    foreach($data as $value=>$name)
                    {
                        echo CHtml::tag('li',array('id'=>$value),CHtml::encode($name),true);
                        //$qvvalues[]=array('label' => $name, 'value' => $value);
                    }                                        
                }
                
                //echo json_encode($qvvalues);
                
                Yii::app()->end();
            }else {
                throw new CHttpException(400, 'Invalid request.');
            }
        }


        public function actionLoadMaps(){
            $data = Yii::app()->db->createCommand()
                    ->select('qvv_id_from,qvv_id_to,qvv_fieldValue')
                    ->from('tbl_qvmaps')
                    ->join('tbl_qvvalues','tbl_qvmaps.qvv_id_to = tbl_qvvalues.qvv_id')
                    ->where('qvv_id_from = :qvv_id_from',array(':qvv_id_from'=>$_POST['act_id_from']))
                    ->queryAll();

            if(count($data)<1){
                echo CHtml::tag('li',array('id'=>1,'cssClass'=>'ui-selectee'),CHtml::encode('None'),true);
            }

            foreach($data as $value)
            {
                //'class'=>'ui-selectee'
                echo CHtml::tag('li',array('id'=>$value['qvv_id_from'].'xx'.$value['qvv_id_to']),CHtml::encode($value['qvv_fieldValue']),true);
            }

        }

        public function actionAddMapValues(){
            if(isset($_POST['act_id_from'])){
                if(!$_POST['act_id_from']==0 AND !$_POST['act_id_to']==0){
                    $addValues = explode(',',$_POST['act_id_to']);
                    foreach($addValues AS $Value){
                        if(!$Value == 0 AND !is_Object(Qvmaps::model()->find('qvv_id_from = :qvv_id_from AND qvv_id_to = :qvv_id_to',array(':qvv_id_from'=>$_POST['act_id_from'],':qvv_id_to'=>$Value)))){
                            $saveRecord = new Qvmaps();
                            $saveRecord->qvv_id_from = $_POST['act_id_from'];
                            $saveRecord->qvv_id_to = $Value;
                            $saveRecord->save();
                        }
                    }
                    $this->actionLoadMaps();
                }
            }            
        }

        public function actionDelMapValues(){
            var_dump($_POST);
        }
}
